package com.example.aspect;


import com.example.annotation.LogOperation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * AOP  切面，用于记录操作日志
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 在带有 @LogOperation 注解的方法执行成功后记录操作日志
     *
     * @param joinPoint 切入点对象，包含被拦截方法的信息
     * @param result    被拦截方法的返回值
     */
    @AfterReturning(pointcut = "@annotation(com.example.annotation.LogOperation)", returning = "result")
    public void logOperation(JoinPoint joinPoint, Object result) {
        // 获取方法签名和方法对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        // 获取 @LogOperation 注解实例
        LogOperation annotation = method.getAnnotation(LogOperation.class);

        // 构建日志信息
        Map<String, Object> logInfo = new HashMap<>();
        logInfo.put("operation", annotation.value());
        logInfo.put("method", method.getName());
        logInfo.put("parameters", joinPoint.getArgs());
        logInfo.put("result", result);
        logInfo.put("timestamp", System.currentTimeMillis());

        // 存入Redis列表（使用List结构，方便后续批量获取）
        redisTemplate.opsForList().rightPush("operation_logs", logInfo);
    }
}
